package com.cloud.phone.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.media.ExifInterface;

import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.view.TsUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageCropper {

    public static void cropImage(File imageFile,String fileName, Rect rect) throws IOException {
        // 读取图片
        try {
            FileInputStream fis = new FileInputStream(imageFile);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);

            Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.width(), rect.height());

            // 保存裁剪后的图片
            File outputFile = new File(imageFile.getParentFile(), fileName+"_crop.jpg");
            FileOutputStream fos = new FileOutputStream(outputFile);
            croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

            fos.flush();
            fos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
            TsUtils.showTips("裁剪出错："+e.getCause()+""+e.getMessage());
        }
    }


    public static boolean cropImage(Bitmap bitmap,String fileName,Rect rect){
        boolean isCropSuccess = false;
        try {
            Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.width(), rect.height());

            // 保存裁剪后的图片
            File outputFile = new File(BingTopDama.getRootDirectory(), fileName+"_crop.jpg");
            FileOutputStream fos = new FileOutputStream(outputFile);
            croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

            fos.flush();
            fos.close();
            isCropSuccess=true;
        } catch (IOException e) {
            e.printStackTrace();
            isCropSuccess=false;
            MsgTaskManger.showLog("裁剪出错：\n"+e.getCause()+""+e.getMessage());
        }
        return isCropSuccess;
    }

    private static int getImageOrientation(File imageFile) throws IOException {
        ExifInterface exifInterface = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270;
            default:
                return 0;
        }
    }
}
